<!--
 * @Date: 2022-03-16 11:38:43
 * @Author: 陶子
 * @LastEditTime: 2023-06-13 09:19:54
 * @FilePath: \jk_one-stop_pc\src\views\warehouseManagement\stockTask\inStock\batchIn.vue
 * @pageName: 这是--(批量入库表单)--页面
-->
<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['仓库管理', '库管任务']"
      marginBottom="10px"
      currentMenu="批量入库"
    ></crumbs>
    <div class="form-body">
      <div class="cards-box">
        <a-card title="基本信息" :bordered="false" style="margin-top: 12px">
          <a-form-model ref="ruleFormTwo" :model="buildForm" :rules="rules">
            <a-row>
              <a-col :span="7">
                <a-form-model-item label="入库人" style="width: 100%" prop="operateUserId">
                  <a-select v-model="buildForm.operateUserId" class="row-input" placeholder="请选择" disabled>
                    <a-select-option :value="item.id" v-for="item in peopleList" :key="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="1"></a-col>
              <a-col :span="7">
                <a-form-model-item label="入库日期" style="width: 100%" prop="operateTime">
                  <a-date-picker v-model="buildForm.operateTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="1"></a-col>
              <a-col :span="7">
                <a-form-model-item label="入库仓库" style="width: 100%" prop="warehouseId">
                  <a-select
                    show-search
                    v-model="buildForm.warehouseId"
                    class="row-input"
                    placeholder="请选择"
                    :filter-option="filterOption"
                  >
                    <a-select-option :value="item.value" v-for="item in stockLIst" :key="item.value">
                      {{ item.text }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="23">
                <a-form-model-item label="入库原因" style="width: 100%">
                  <a-textarea v-model="buildForm.remark" :maxLength="500" placeholder="请输入" />
                </a-form-model-item>
              </a-col>
              <a-col :span="23">
                <a-form-model-item label="附件" style="flex: 1">
                  <file-upload :ids="buildForm.dingFileInfo" @getFileList="getFileList"></file-upload>
                  <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，大小不可超过20M</p>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
        <a-card title="入库明细" :bordered="false" style="margin-top: 12px">
          <j-editable-table
            ref="materialTable"
            :loading="goodsTable.loading"
            :columns="goodsTable.columns"
            :dataSource="goodsTable.dataSource"
            :maxHeight="300"
            :rowNumber="false"
            :rowSelection="true"
            @selectRowChange="selectRowChange"
          >
            <template v-slot:spec="props">
              <div class="comp-normal" :title="props.value || '-'">
                {{ props.value || '-' }}</div>
            </template>
            <template v-slot:boundGoodsNumText="props">
              <div class="comp-normal" :title="showAllText(props.index, 'boundGoodsNumText')">
                {{ showText(props.index, 'boundGoodsNumText') }}</div
              >
            </template>
            <template v-slot:completeGoodsNumText="props">
              <div class="comp-normal" :title="showAllText(props.index, 'completeGoodsNumText')">
                {{ showText(props.index, 'completeGoodsNumText') }}</div
              >
            </template>
            <template v-slot:boundGoodsNumTxtAssistUnit="props">
              <div class="comp-normal" :title="props.value">{{ props.value || '-' }}</div>
            </template>
            <template v-slot:completeGoodsNumTxtAssistUnit="props">
              <div class="comp-normal" :title="props.value">{{ props.value || '-' }}</div>
            </template>
            <template v-slot:goodsQualifiedNum="props">
              <!-- <a-input v-model="props.text" placeholder="请输入" :suffix="checkUnit(props.index)" @input="(e) => inputNum(e, props, 'goodsQualifiedNum')"></a-input> -->
              <a-input
                v-model="props.text"
                @input="(e) => inputNum(e, props, 'goodsQualifiedNum')"
                placeholder="请输入"
              >
                <div
                  slot="addonAfter"
                  style="width: 80px; overflow: hidden; white-space: nowrap; text-overflow: ellips"
                >
                  <a-select
                    :default-value="dataSourceItem(props, 'selectUnitQ')"
                    @change="(e) => qualifiedChange(e, props)"
                    style="width: 80px"
                  >
                    <a-select-option v-for="unit in dataSourceItem(props, 'unitList')" :value="unit.id" :key="unit.id">
                      {{ unit.unit }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-input>
            </template>
            <template v-slot:goodsScrapNum="props">
              <!-- <a-input v-model="props.text" placeholder="请输入" :suffix="checkUnit(props.index)" @input="(e) => inputNum(e, props, 'goodsScrapNum')"></a-input> -->
              <a-input v-model="props.text" @input="(e) => inputNum(e, props, 'goodsScrapNum')" placeholder="请输入">
                <div
                  slot="addonAfter"
                  style="width: 80px; overflow: hidden; white-space: nowrap; text-overflow: ellips"
                >
                  <a-select
                    :default-value="dataSourceItem(props, 'selectUnitS')"
                    @change="(e) => scrapNumChange(e, props)"
                    style="width: 80px"
                  >
                    <a-select-option v-for="unit in dataSourceItem(props, 'unitList')" :value="unit.id" :key="unit.id">
                      {{ unit.unit }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-input>
            </template>
          </j-editable-table>
        </a-card>
      </div>
    </div>
    <div class="footer-submit form-footer">
      <div class="footLeft" v-if="inValue">
        <div class="taskText">完成任务</div>
        <a-switch v-model="buildForm.complete" />
      </div>
      <a-button type="primary" @click="handleSubmit" :loading="submitLoading"> 提交 </a-button>
    </div>
    <!-- 完成modal -->
    <a-modal
      :bodyStyle="{ padding: '32px 32px 24px', boxSizing: 'border-box' }"
      :maskClosable="false"
      v-model="overVisible"
      :closable="false"
      on-ok="setLimit"
      width="460px"
    >
      <template slot="footer">
        <a-button key="back" @click="cancleOverSubmit"> 取消 </a-button>
        <a-button key="submit" @click="sureOverSubmit" type="primary"> 确定 </a-button>
      </template>
      <div class="modalTopBox">
        <a-icon type="question-circle" style="color: #faad14; font-size: 22px" />
        <span>入库完成后无法对任务再次入库。</span>
      </div>
      <div class="bigFont">确定入库完成吗？</div>
    </a-modal>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { querySysSet } from '@/api/erpApi'
import moment from 'moment'
import { clearNoNum, numFormat, accAdd, subStrText, accMul, accDivMin } from '@/utils/util'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { stockListApi, inLIstDetailApi, batchStockApi } from '@/api/erpApi'
export default {
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
  },
  data() {
    return {
      jkeForm: {
        title: '批量入库',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      inValue: false,
      overVisible: false,
      numFormat,
      stockLIst: [],
      peopleList: [],
      buildForm: {
        operateType: '1',
        dingFileInfo: '',
        complete: false,
      },
      formatParams: {},
      submitLoading: false, // 提交loading
      rules: {
        operateUserId: [{ required: true, message: '请选择', trigger: 'change' }],
        operateTime: [{ required: true, message: '请选择', trigger: 'change' }],
        warehouseId: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: 'unitList',
            key: 'unitList',
            type: FormTypes.hidden,
          },
          {
            title: 'rateQ',
            key: 'rateQ',
            type: FormTypes.hidden,
          },
          {
            title: 'rateS',
            key: 'rateS',
            type: FormTypes.hidden,
          },
          {
            title: 'rateQOld',
            key: 'rateQOld',
            type: FormTypes.hidden,
          },
          {
            title: 'rateSOld',
            key: 'rateSOld',
            type: FormTypes.hidden,
          },
          {
            title: 'selectUnitQ',
            key: 'selectUnitQ',
            type: FormTypes.hidden,
          },
          {
            title: 'selectUnitS',
            key: 'selectUnitS',
            type: FormTypes.hidden,
          },
          {
            title: 'goodsId',
            width: '20%',
            key: 'goodsId',
            type: FormTypes.hidden,
          },
          {
            title: 'taskDetailId',
            width: '20%',
            key: 'taskDetailId',
            type: FormTypes.hidden,
          },
          {
            title: '物品编号',
            width: '15%',
            key: 'goodsCode',
            type: FormTypes.normal,
          },
          {
            title: '物品名称',
            width: '11%',
            key: 'goodsName',
            type: FormTypes.normal,
          },
          {
            title: '规格',
            width: '8%',
            key: 'spec',
            type: FormTypes.slot,
            slotName: 'spec',
          },
          {
            title: '总应入',
            width: '8%',
            key: 'boundGoodsNumText',
            type: FormTypes.slot,
            slotName: 'boundGoodsNumText',
          },
          {
            title: '已入库基本单位数量',
            width: '180px',
            key: 'completeGoodsNumText',
            type: FormTypes.slot,
            slotName: 'completeGoodsNumText',
          },
          {
            title: '总应入(F)',
            width: '12%',
            key: 'boundGoodsNumTxtAssistUnit',
            type: FormTypes.slot,
            slotName: 'boundGoodsNumTxtAssistUnit',
          },
          {
            title: '已入库数量(F)',
            width: '15%',
            key: 'completeGoodsNumTxtAssistUnit',
            type: FormTypes.slot,
            slotName: 'completeGoodsNumTxtAssistUnit',
          },
          {
            title: '本次入库合格品',
            width: '20%',
            key: 'goodsQualifiedNum',
            type: FormTypes.slot,
            isrequired: true,
            placeholder: '请输入${title}',
            slotName: 'goodsQualifiedNum',
            defaultValue: '',
            validateRules: [
              {
                pattern: /[0-9]+[0-9]*/,
                message: '${title}不能为空',
              },
              {
                required: true,
                message: '请输入${title}数',
              },
            ],
          },
          {
            title: '本次入库报废品',
            width: '20%',
            key: 'goodsScrapNum',
            type: FormTypes.slot,
            isrequired: true,
            placeholder: '请输入${title}',
            slotName: 'goodsScrapNum',
            defaultValue: '',
            validateRules: [
              {
                pattern: /[0-9]+[0-9]*/,
                message: '${title}不能为空',
              },
              {
                required: true,
                message: '请输入${title}数',
              },
            ],
          },
        ],
      },
      selectRowKeys: [],
    }
  },
  methods: {
    initForm(query) {
      this.jkeForm.visible = true
      let user = localStorage.getItem('pro__Login_Userinfo')
      let peopleObj = {
        name: JSON.parse(user).value.realname,
        id: JSON.parse(user).value.id,
      }
      this.peopleList = [peopleObj]
      this.buildForm.operateUserName = JSON.parse(user).value.realname
      this.buildForm.operateUserId = JSON.parse(user).value.id
      let nowDate = new Date()
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1
      let day = nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate.getDate()
      let currentTime = year + '-' + month + '-' + day
      this.buildForm.operateTime = moment(currentTime, 'YYYY-MM-DD')
      let itemInfo = query
      this.buildForm.operateTaskType = itemInfo.type
      this.buildForm.operateTaskId = itemInfo.id
      this.getInStockList()
      this.getInStockDetailList(itemInfo.id)
      let inObj = {
        key: 'inboundTaskCompleteBtnFlag',
      }
      this.getSysState(inObj, 'inValue')
    },
    // 选择合格品单位
    qualifiedChange(e, props) {
      let { unitList, rateQOld,  goodsQualifiedNum } = this.$refs.materialTable.getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      let old_num = goodsQualifiedNum ? accMul(goodsQualifiedNum, rateQOld) : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      console.log('goodsQualifiedNum',goodsQualifiedNum,'-','rateQOld',rateQOld);
      this.$refs.materialTable.setValues([
        {
          rowKey: props.rowId,
          values: {
            rateQ: unit.conversionRate,
            rateQOld: unit.conversionRate,
            selectUnitQ: e,
            goodsQualifiedNum: goodsQualifiedNum ? accDivMin(old_num, unit.conversionRate) : '0' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */
          },
        },
      ])
    },
    // 选择报废品单位
    scrapNumChange(e, props) {
      let { unitList, rateSOld, goodsScrapNum } = this.$refs.materialTable.getValuesSync({
        validate: false,
        rowIds: [props.rowId],
      }).values[0]
      let unit = JSON.parse(unitList).find((item) => item.id == e)
      let old_num = goodsScrapNum ? accMul(goodsScrapNum, rateSOld) : '' /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
      this.$refs.materialTable.setValues([
        {
          rowKey: props.rowId,
          values: {
            rateS: unit.conversionRate,
            rateSOld: unit.conversionRate,
            selectUnitS: e,
            goodsScrapNum: goodsScrapNum ? accDivMin(old_num, unit.conversionRate) : '0' /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */
          },
        },
      ])
    },
    dataSourceItem(props, key) {
      let item = this.goodsTable.dataSource[props.index]
      let val = item[key]
      if (key == 'unitList') {
        return JSON.parse(val)
      } else {
        return val
      }
    },
    getSysState(params, valueType) {
      querySysSet(params).then((res) => {
        if (res.success) {
          let resConter = res.result
          if (resConter == 'enable') {
            this[valueType] = true
          } else {
            this[valueType] = false
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    showText(index, key) {
      let item = this.goodsTable.dataSource[index]
      if (item[key] == '-') {
        return `--`
      } else {
        return `${item[key]}${subStrText(item.assistUnit, 2)}`
      }
    },
    showAllText(index, key) {
      let item = this.goodsTable.dataSource[index]
      if (item[key] == '-') {
        return `--`
      } else {
        return `${item[key]}${item.assistUnit}`
      }
    },
    getInStockList() {
      stockListApi().then((res) => {
        if (res.success) {
          this.stockLIst = res.result
        } else {
          this.$antdMessage.warning(res.message)
        }
      })
    },
    getInStockDetailList(taskId) {
      this.goodsTable.loading = true
      let detailObj = {
        taskId,
      }
      inLIstDetailApi(detailObj).then(async (res) => {
        if (res.success) {
          this.goodsTable.dataSource = []
          let resArr = res.result
          for (let item of resArr) {
            const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
            item.unitList = JSON.stringify(unitRes.result)
            item.rateQ = 1
            item.rateS = 1
            item.rateQOld = 1
            item.rateSOld = 1
            item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id
            item.selectUnitS = unitRes.result[unitRes.result.length - 1].id

            item.goodsQualifiedNum = ''
            item.goodsScrapNum = ''
            item.goodsScrapNum = '0'
            item.goodsQualifiedNum = '0'
            this.goodsTable.dataSource.push(item)
          }
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.goodsTable.loading = false
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    checkUnit(index) {
      let item = this.goodsTable.dataSource[index]
      return `${subStrText(item.assistUnit, 2)}`
    },
    selectRowChange(ids) {
      this.selectRowKeys = ids
    },
    inputNum(e, props, inputKey) {
      let newNum = clearNoNum(e.target.value)
      this.$refs.materialTable.setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 amount 是你 columns 中配置的 key
            [inputKey]: newNum,
          },
        },
      ])
      let { err, values } = this.$refs.materialTable.getValuesSync({ validate: true, rowIds: [props.rowId] })
    },
    goBack() {
      this.jkeForm.visible = false
    },

    /* 获取附件 */
    getFileList(v) {
      this.buildForm.dingFileInfo = v
      console.log('上传的附件id：', v)
    },
    handleSubmit() {
      let that = this
      that.$refs.ruleFormTwo.validate((valid) => {
        if (valid) {
          let { error, values } = that.$refs.materialTable.getValuesSync({
            validate: true,
            rowIds: that.selectRowKeys,
          })
          console.log(error, values)
          if (values.length == 0) {
            that.$antdMessage.warning('请选择入库物品')
            return
          } else {
            if (error == 0) {
              console.log('校验通过', values)
              let goodsList = []
              for (let i = 0; i < values.length; i++) {
                let obj = {}
                let item = values[i]
                let goodsNum = accAdd(item.goodsQualifiedNum, item.goodsScrapNum)
                if (goodsNum == 0) {
                  this.$antdMessage.warning(`所选第${i + 1}条数据，入库总数量需大于零`)
                  return
                }
                console.log('dangqianglj:', item)
                obj.goodsId = item.goodsId
                obj.taskDetailId = item.taskDetailId
                obj.goodsNum = goodsNum
                obj.goodsQualifiedNum = accMul(item.goodsQualifiedNum, item.rateQ)
                obj.goodsScrapNum = accMul(item.goodsScrapNum, item.rateS)
                goodsList.push(obj)
              }

              let params = {
                ...this.buildForm,
                goodsList,
              }
              params.operateTime = moment(params.operateTime).format('YYYY-MM-DD')
              console.log('当前所有的参数是：', params)
              this.formatParams = { ...params }
              if (params.complete) {
                this.overVisible = true
              } else {
                this.submitLoading = true
                this.requsetFace()
              }
            }
          }
        } else {
          return false
        }
      })
    },
    cancleOverSubmit() {
      this.overVisible = false
      this.submitLoading = false
    },
    sureOverSubmit() {
      this.overVisible = false
      this.submitLoading = true
      this.requsetFace()
    },
    requsetFace() {
      batchStockApi(this.formatParams).then((res) => {
        if (res.success) {
          this.$antdMessage.success('物品已入库')
          this.$emit('refresh')
          this.goBack()
        } else {
          this.$antdMessage.warning(res.message)
        }
        this.submitLoading = false
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.item-wrap {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.item-wrap:nth-of-type(n + 2) {
  margin-top: 40px;
}
.detail-item {
  width: 30%;
}
.bd-line {
  height: 1px;
  background: @greyBorder;
  margin: -12px -40px 24px -40px;
}
.cards-box {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.footLeft {
  margin-right: 50px;
  .taskText {
    margin-right: 5px;
    color: #191f25;
    font-size: 15px;
  }
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.modalTopBox {
  .flex(flex-start, center);
  margin-bottom: 8px;
  span {
    margin-left: 16px;
    display: block;
    overflow: hidden;
    font-weight: 500;
    font-size: 16px;
    line-height: 1.4;
    color: rgba(0, 0, 0, 1);
  }
}
.bigFont {
  font-size: 16px;
  color: rgba(0, 0, 0, 1);
  box-sizing: border-box;
  padding-left: 39px;
  margin-bottom: 8px;
  font-weight: 500;
}
.smallFont {
  font-size: 14px;
  box-sizing: border-box;
  padding-left: 12px;
}
</style>
